/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.org;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.DepartmentUserException;
import com.je.rbac.service.organization.RbacOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/je/rbac/cloud/organization")
public class RbacOrgController extends AbstractPlatformController {

    @Autowired
    private RbacOrganizationService rbacOrganizationService;

    @Override
    @RequestMapping(value = {"/load"}, method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "loadOrg", operateTypeName = "查看机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Page page = this.manager.load(param, request);
        return page == null ? BaseRespResult.successResultPage(Lists.newArrayList(), 0L) : BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "saveOrg", operateTypeName = "保存机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) throws AccountException {

        //获取新增数据
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (dynaBean == null) {
            return BaseRespResult.errorResult("请选择需要保存的机构！");
        }
        //需验证机构名称是否重复。
        if (Strings.isNullOrEmpty(dynaBean.getStr("ORG_RESOURCETABLE_CODE")) || Strings.isNullOrEmpty(dynaBean.getStr("ORG_NAME")) || Strings.isNullOrEmpty(dynaBean.getStr("ORG_CODE"))) {
            return BaseRespResult.errorResult("请设置相关参数！");
        }
        if (!rbacOrganizationService.checkOrgNameUnique(dynaBean)) {
            return BaseRespResult.errorResult("机构名称重复，请修改！");
        }
        if (!rbacOrganizationService.checkOrgCodeUnique(dynaBean)) {
            return BaseRespResult.errorResult("机构编码重复，请修改！");
        }
        if (!rbacOrganizationService.checkResourceTableCodeUnique(dynaBean)) {
            return BaseRespResult.errorResult("所选资源表已被其他机构绑定，请重新选择！");
        }
        try {
            return BaseRespResult.successResult(rbacOrganizationService.doSave(dynaBean));
        } catch (DepartmentUserException e) {
            throw new PlatformException("数据保存失败！", PlatformExceptionEnum.UNKOWN_ERROR, e);
        }
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "updateOrg", operateTypeName = "更新机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) throws AccountException {
        try {
            //获取修改数据
            DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
            if (dynaBean == null) {
                return BaseRespResult.errorResult("请选择需要修改的机构！");
            }

            //需验证，资源表编码，机构名称是否重复。
            if (Strings.isNullOrEmpty(dynaBean.getStr("ORG_RESOURCETABLE_NAME")) || Strings.isNullOrEmpty(dynaBean.getStr("ORG_NAME")) || Strings.isNullOrEmpty(dynaBean.getStr("ORG_CODE"))) {
                return BaseRespResult.errorResult("请设置相关参数！");
            }
            if (!rbacOrganizationService.checkOrgNameUnique(dynaBean)) {
                return BaseRespResult.errorResult("机构名称重复，请修改！");

            }
            if (!rbacOrganizationService.checkOrgCodeUnique(dynaBean)) {
                return BaseRespResult.errorResult("机构编码重复，请修改！");
            }
            if (!rbacOrganizationService.checkResourceTableCodeUnique(dynaBean)) {
                return BaseRespResult.errorResult("所选资源表已被其他机构绑定，请重新选择！");
            }
            rbacOrganizationService.updateDeptNameByOrgId(dynaBean);
            return BaseRespResult.successResult(manager.doUpdate(param, request).getValues());
        } catch (PlatformException e) {
            throw new PlatformException("数据修改失败！", PlatformExceptionEnum.UNKOWN_ERROR, e);
        }
    }

    /**
     * 启用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/enable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "enableOrg", operateTypeName = "启用机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult<String> enable(HttpServletRequest request) throws AccountException {
        String orgIds = getStringParameter(request, "orgIds");

        if (Strings.isNullOrEmpty(orgIds)) {
            return BaseRespResult.errorResult("请选择需要启用的机构！");
        }
        //需验证是否为系统级别数据
        if (!rbacOrganizationService.checkSystemUnique(orgIds)) {
            return BaseRespResult.errorResult("系统级机构不允许操作！");
        }
        rbacOrganizationService.enableOrgs(orgIds);
        return BaseRespResult.successResult("启用成功！");
    }

    /**
     * 禁用
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/disable"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "disableOrg", operateTypeName = "禁用机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult disable(HttpServletRequest request) throws AccountException {
        String orgIds = getStringParameter(request, "orgIds");
        if (Strings.isNullOrEmpty(orgIds)) {
            return BaseRespResult.errorResult("请选择需要禁用的机构！");
        }
        //需验证是否为系统级别数据
        if (!rbacOrganizationService.checkSystemUnique(orgIds)) {
            return BaseRespResult.errorResult("系统级机构不允许操作！");
        }
        rbacOrganizationService.disableOrgs(orgIds);
        return BaseRespResult.successResult("禁用成功！");
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/remove"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "机构管理", operateTypeCode = "removeOrg", operateTypeName = "移除机构", logTypeCode = "systemManage", logTypeName = "系统管理")
    public BaseRespResult remove(HttpServletRequest request) throws AccountException {
        String orgIds = getStringParameter(request, "orgIds");
        if (Strings.isNullOrEmpty(orgIds)) {
            return BaseRespResult.errorResult("请选择要删除的机构！");
        }
        //需验证是否为系统级别数据
        if (!rbacOrganizationService.checkSystemUnique(orgIds)) {
            return BaseRespResult.errorResult("系统级机构不允许操作！");
        }
        try {
            rbacOrganizationService.removeOrg(orgIds);
        } catch (Exception e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("删除成功！");
    }

}
